package com.finalab.yueqiu.service.token;


import com.finalab.yueqiu.constant.EntityType;
import com.finalab.yueqiu.constant.RedisKeyType;
import com.finalab.yueqiu.dao.redis.JedisDAO;
import com.finalab.yueqiu.exception.ServerErrorException;
import com.finalab.yueqiu.util.RedisKeyUtil;
import com.finalab.yueqiu.util.SaltUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Transaction;

import java.io.IOException;
import java.util.List;

/**
 * @author 莉安
 */
@Service
public class TokenServiceImpl implements TokenService{

    @Autowired
    JedisDAO jedisDAO;

    private static final int TOKEN_LAST_TIME =  60*60*24*14;
    /**
     * 不同类型的操作返回值原来不一样..例如的递增删除是1，但是set又是OK
     */
    private static final String TRANSACTION_SUCCEED_TAG = "OK";


    @Override
    public String addToken(int id){
        Transaction tx = jedisDAO.multi();
        String token = SaltUtil.getSalt();
        String key = RedisKeyUtil.getKey(id, EntityType.USER.getValue(), RedisKeyType.TOKEN);
        tx.setex(token, TOKEN_LAST_TIME, key);
        tx.setex(key, TOKEN_LAST_TIME, token);
        List<Object> result = jedisDAO.getTx(tx);
        boolean flag = (result.size() == 2 ) && TRANSACTION_SUCCEED_TAG.equals(result.get(0)) && TRANSACTION_SUCCEED_TAG.equals(result.get(1));
        if(!flag){
            throw new ServerErrorException("增加token失败！");
        }
        try {
            tx.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return token;
    }

    @Override
    public String getToken(int id){
        return jedisDAO.get(String.valueOf(id));
    }

    @Override
    public String getToken(String token){
        return jedisDAO.get(token);
    }

    @Override
    public boolean deleteToken(int id){
        String key = RedisKeyUtil.getKey(id, EntityType.USER.getValue(), RedisKeyType.TOKEN);
        String token = getToken(key);
        Transaction tx = jedisDAO.multi();
        tx.del(key);
        tx.del(token);
        List<Object> result = jedisDAO.getTx(tx);
        boolean flag = (result.size() == 2 ) && 1 == (Long) result.get(0)
                && 1 == (Long) result.get(1);
        if(!flag){
            System.out.println(result.get(0) + ":" + result.get(1));
            return false;
        }
        try {
            tx.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

}
